#include "importdcmfilethread.h"
#include "importstudymodel.h"
#include "../../ImageAcquisitor/ImageAcquisitor/global.h"
#include "qftp.h"

#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dcuid.h"
#include "dcmtk/dcmsr/dsrtypes.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSettings>
#include <QFile>
#include <QDebug>

ImportDcmFileThread::ImportDcmFileThread(QObject *parent) :
    abort(false),
    ftp(new QFtp(this)),
    QThread(parent)
{
    connect(ftp, SIGNAL(commandFinished(int,bool)),
            this, SLOT(onCmdFinished(int,bool)));
    connect(ftp, SIGNAL(dataTransferProgress(qint64,qint64)),
            this, SLOT(onProgress(qint64,qint64)));
}

ImportDcmFileThread::~ImportDcmFileThread()
{
}

void ImportDcmFileThread::initFtp()
{
    if (ftp->state() == QFtp::Unconnected) {
        QSettings s(LOCAL_NETWORK_CONFIG, QSettings::IniFormat);
        s.setIniCodec(QSETTINGS_CODEC_NAME);
        ftp->connectToHost(s.value(NETWORK_FTP_HOST).toString(), s.value(NETWORK_FTP_PORT).toInt());
        ftp->login(s.value(NETWORK_FTP_USER).toString(), s.value(NETWORK_FTP_PWD).toString());
        ftp->setTransferMode(QFtp::Passive);
    }
}

void ImportDcmFileThread::onCmdFinished(int id, bool ok)
{
    QFile *f = snds.take(id);
    if (f) {
        emit fileTransferred();
        delete f;
    }

    qDebug() << id << "\t" << ok << "\t" << ftp->errorString();
}

void ImportDcmFileThread::onProgress(qint64 cur, qint64 total)
{
    qDebug() << cur << "\t" << total;
}

void ImportDcmFileThread::run()
{
    QSqlDatabase db = QSqlDatabase::database();
    QSqlQuery q(db);

    abort = false;

    initFtp();

    foreach (StudyRecord *study, studyList) {
        if (abort) break;

        q.prepare("INSERT INTO study_t(study_iuid, pati_id, pati_name, pati_sex, pati_birth, pati_age, pati_adid, pati_alert, acc_num, study_time, modality, body_part, insti_id_fk, task_phy_id_fk, stat_id_fk, study_desc)"
                  " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        q.addBindValue(study->studyIUid);
        q.addBindValue(study->patientId);
        q.addBindValue(study->patientName);
        q.addBindValue(study->patientSex);
        q.addBindValue(study->patientBirth);
        q.addBindValue(study->patientAge);
        q.addBindValue(study->admissionId);
        q.addBindValue(study->medicalAlerts);
        q.addBindValue(study->accNumber);
        q.addBindValue(study->studyTime);
        q.addBindValue(study->modality);
        q.addBindValue(study->bodyPart);
        q.addBindValue("10001");
        q.addBindValue("30001");
        q.addBindValue("0001");
        q.addBindValue(study->studyDesc);

        if (!q.exec()) {
            study->status = q.lastError().text();
        }

        ftp->mkdir(study->studyIUid);
        ftp->cd(study->studyIUid);

        foreach (ImageRecord *image, study->imageList) {
            q.prepare("INSERT INTO image_t(image_iuid, image_cuid, series_iuid, study_iuid_fk)"
                      "VALUES(?,?,?,?)");
            q.addBindValue(image->imageIUid);
            q.addBindValue(image->imageCUid);
            q.addBindValue(image->seriesIUid);
            q.addBindValue(image->studyIUid);
            if (q.exec()) {
                image->ok = true;
            }

            QFile *f = new QFile(image->file);
            if (f->open(QIODevice::ReadOnly)) {
                snds.insert(ftp->put(f, image->imageIUid+".dcm", QFtp::Binary), f);
            } else {
                qDebug() << f->errorString();
            }
        }

        ftp->cdup();

        emit resultReady(study);
    }

    while (ftp->hasPendingCommands()) msleep(100);
}
